<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\12 0012
 * Time: 15:21
 */

namespace app\Lib\Model\AdminAuth\Authorization;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\AdminAuth\Authorization\BindingAuthBaseHandle;
use app\Lib\InterfaceIn\AdminAuth\MenuAuthHandle;
use app\Lib\InterfaceIn\User\UserHandle;
use app\Lib\Model\AdminAuth\GetAuthorization\GetAuthorization;

abstract class BindingAuthBase implements BindingAuthBaseHandle
{
    protected $authArray;
    /** @var UserHandle $opUser */
    protected $opUser;
    protected $opUserAuthArray= [];

    /**
     * 设置授权权限组
     * @param $authArray
     * @return $this
     */
    public function setAuthArray($authArray)
    {
        $this->authArray = $authArray;
        return $this;
    }

    /**
     * 设置操作人
     * @param UserHandle $opUser
     * @return $this
     */
    public function setOpUser(UserHandle $opUser)
    {
        $this->opUser = $opUser;
        return $this;
    }

    /**
     * 获取要授权的权限
     * @return array
     * @throws BlException
     */
    protected function getAuth(){
        $authData = [];
        /*操作人是否拥有要授权的所有权限*/
        $superAuth = false;
        if($this->opUser->getRoleClass()->isSuperAdministrator()){
            $superAuth = true;
        };
        foreach ($this->authArray as $v){
            /** @var  MenuAuthHandle $v */
            if(!($v instanceof MenuAuthHandle)){
                throw new BlException('授权参数错误');
            }
            /*操作人权限验证*/
            if($superAuth!=true){
                $this->checkAuthContain($v);
            }
            $authData[] = $v->getMenuId();
        }
        return $authData;
    }

    /**
     * 验证操作人是否有权限
     * @param MenuAuthHandle $v
     * @return bool
     * @throws BlException
     */
    private function checkAuthContain(MenuAuthHandle $v){
        $authArray= $this->getOpUserAuth();
        if(!isset($authArray[$v->getMenuId()])){
            throw new BlException('你没有'.$v->getName().'的权限');
        }
        return true;
    }

    /**
     * 获取操作人的权限
     * @return array
     */
    private function getOpUserAuth(){
        $authArray = [];
        if(empty($this->opUserAuthArray)){
            $data = (new GetAuthorization($this->opUser))->run();
            foreach ($data as $v){
                if($v instanceof MenuAuthHandle){
                    $authArray[$v->getMenuId()] = $v->getMenuId();
                }
            }
            $this->opUserAuthArray = $authArray;
        }
        return $this->opUserAuthArray;
    }


}